angular.module('app')
.directive('againUpload', ['$http','$rootScope', function($http,$rootScope){
    return {
        restrict: 'A',
        templateUrl: 'tpl/againUpload.html',
        replace: true,
        controller: function($scope, $element, $attrs, $transclude) {
            hljs.initHighlightingOnLoad();
        },
        link: function($scope, iElm, iAttrs, controller) {
            $http({
                url:$rootScope.baseUrl+"Upload/getToken",
                method:"post",
            }).then(function(res){
                if(res.data.code==200){
                    $scope.token=res.data.data.token;
                    var $container=$(iElm).find(".containerAgainDiv");
                    var containerID=$container.attr("id");
                    var pickfilesID=$container.find("a").attr("id");
                    var index=pickfilesID.split("pickfilesAgain")[1].slice(-1);
                    var randomStr=containerID.split("containerAgain")[1].slice(0,-1);

                    var uploader = Qiniu.uploader({
                        runtimes: 'html5,flash,html4',
                        browse_button:pickfilesID,
                        container: containerID,
                        drop_element: containerID,
                        max_file_size: '1000mb',
                        flash_swf_url: '../scripts/Moxie.swf',
                        dragdrop: true,
                        chunk_size: '5mb',
                        multi_selection: !(mOxie.Env.OS.toLowerCase()==="ios"),
                        uptoken:$scope.token,
                        domain:"http://video.mfxx.dunheinfo.com/",
                        get_new_uptoken: false,
                        dragdrop: true,
                        unique_names: false,
                        save_key: false,
                        auto_start: true,
                        log_level: 5,
                        init: {
                            'FilesAdded': function(up, files) {
                                $(iElm).find('table').show();
                                $(iElm).find('#success').hide();
                                plupload.each(files, function(file) {
                                    var progress = new FileProgress(file,'fsUploadProgressAgain'+randomStr+index);
                                    progress.setStatus("等待...");
                                    progress.bindUploadCancel(up);
                                });
                                $(iElm).find("#"+pickfilesID).hide();
                            },
                            'BeforeUpload': function(up, file) {
                                var progress = new FileProgress(file,'fsUploadProgressAgain'+randomStr+index);
                                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                                if (up.runtime === 'html5' && chunk_size) {
                                    progress.setChunkProgess(chunk_size);
                                }
                            },
                            'UploadProgress': function(up, file) {
                                var progress = new FileProgress(file,'fsUploadProgressAgain'+randomStr+index);
                                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                                progress.setProgress(file.percent + "%", file.speed, chunk_size);
                            },
                            'UploadComplete': function() {
                                $(iElm).find('#success').show();
                            },
                            'FileUploaded': function(up, file, info) {
                                var progress = new FileProgress(file,'fsUploadProgressAgain'+randomStr+index);
                                progress.setComplete(up, info);
                                swal("文件上传成功", "", "success");
                            },
                            'Error': function(up, err, errTip) {
                                $(iElm).find('table').show();
                                var progress = new FileProgress(err.file,'fsUploadProgressAgain'+randomStr+index);
                                progress.setError();
                                progress.setStatus(errTip);
                            }
                            ,
                            'Key': function(up, file) {
                                var key=new Date().getTime()+"."+file.type.split("video/")[1];
                                return key;
                            }
                        }
                    });

                    $(iElm).find('#'+containerID).on(
                        'dragenter',
                        function(e) {
                            e.preventDefault();
                            $('#'+containerID).addClass('draging');
                            e.stopPropagation();
                        }
                    ).on('drop', function(e) {
                        e.preventDefault();
                        $(iElm).find('#'+containerID).removeClass('draging');
                        e.stopPropagation();
                    }).on('dragleave', function(e) {
                        e.preventDefault();
                        $(iElm).find('#'+containerID).removeClass('draging');
                        e.stopPropagation();
                    }).on('dragover', function(e) {
                        e.preventDefault();
                        $(iElm).find('#'+containerID).addClass('draging');
                        e.stopPropagation();
                    });



                    $(iElm).find('#show_code').on('click', function() {
                        $('#myModal-code').modal();
                        $('pre code').each(function(i, e) {
                            hljs.highlightBlock(e);
                        });
                    });


                    $('body').on('click', 'table button.btn', function() {
                        $(iElm).find(".chunk-status-tr").toggle();
                    });


                    var getRotate = function(url) {
                        if (!url) {
                            return 0;
                        }
                        var arr = url.split('/');
                        for (var i = 0, len = arr.length; i < len; i++) {
                            if (arr[i] === 'rotate') {
                                return parseInt(arr[i + 1], 10);
                            }
                        }
                        return 0;
                    };

                    $(iElm).find('#myModal-img .modal-body-footer').find('a').on('click', function() {
                        var img = $(iElm).find('#myModal-img').find('.modal-body img');
                        var key = img.data('key');
                        var oldUrl = img.attr('src');
                        var originHeight = parseInt(img.data('h'), 10);
                        var fopArr = [];
                        var rotate = getRotate(oldUrl);
                        if (!$(this).hasClass('no-disable-click')) {
                            $(this).addClass('disabled').siblings().removeClass('disabled');
                            if ($(this).data('imagemogr') !== 'no-rotate') {
                                fopArr.push({
                                    'fop': 'imageMogr2',
                                    'auto-orient': true,
                                    'strip': true,
                                    'rotate': rotate,
                                    'format': 'png'
                                });
                            }
                        } else {
                            $(this).siblings().removeClass('disabled');
                            var imageMogr = $(this).data('imagemogr');
                            if (imageMogr === 'left') {
                                rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
                            } else if (imageMogr === 'right') {
                                rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
                            }
                            fopArr.push({
                                'fop': 'imageMogr2',
                                'auto-orient': true,
                                'strip': true,
                                'rotate': rotate,
                                'format': 'png'
                            });
                        }

                        $(iElm).find('#myModal-img .modal-body-footer').find('a.disabled').each(function() {

                            var watermark = $(this).data('watermark');
                            var imageView = $(this).data('imageview');
                            var imageMogr = $(this).data('imagemogr');

                            if (watermark) {
                                fopArr.push({
                                    fop: 'watermark',
                                    mode: 1,
                                    image: 'http://www.b1.qiniudn.com/images/logo-2.png',
                                    dissolve: 100,
                                    gravity: watermark,
                                    dx: 100,
                                    dy: 100
                                });
                            }

                            if (imageView) {
                                var height;
                                switch (imageView) {
                                    case 'large':
                                        height = originHeight;
                                        break;
                                    case 'middle':
                                        height = originHeight * 0.5;
                                        break;
                                    case 'small':
                                        height = originHeight * 0.1;
                                        break;
                                    default:
                                        height = originHeight;
                                        break;
                                }
                                fopArr.push({
                                    fop: 'imageView2',
                                    mode: 3,
                                    h: parseInt(height, 10),
                                    q: 100,
                                    format: 'png'
                                });
                            }

                            if (imageMogr === 'no-rotate') {
                                fopArr.push({
                                    'fop': 'imageMogr2',
                                    'auto-orient': true,
                                    'strip': true,
                                    'rotate': 0,
                                    'format': 'png'
                                });
                            }
                        });

                        var newUrl = Qiniu.pipeline(fopArr, key);

                        var newImg = new Image();
                        img.attr('src', '../../images/loading.gif');
                        newImg.onload = function() {
                            img.attr('src', newUrl);
                            img.parent('a').attr('href', newUrl);
                        };
                        newImg.src = newUrl;
                        return false;
                    });
                }else if(res.data.code==409){
                    $state.go("access.signin");
                }
            },function(error){
                console.log(error);
            });
        }
    };
}]);